package generator

import (
	"github.com/tealeg/xlsx"
	"time"
	"fmt"
	"github.com/nofuck/reports/parse"
	"github.com/nofuck/reports/utils"
)

type XlsxReport struct {
	Filename string
	header   []string
	body     [][]string
}

func defaultName() string {
	now := time.Now()
	filename := fmt.Sprintf("%s-%d%d%d%d%d%d.xlsx", "miaodi", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
	return filename
}

func (report *XlsxReport) addRowCell(sheet *xlsx.Sheet, li [][]string) {
	for i := 0; i < len(li); i++ {
		row := sheet.AddRow()
		for j := 0; j < len(li[i]); j++ {
			cell := row.AddCell()
			cell.Value = li[i][j]
			cell.FormattedValue()
		}
	}
}

func (report *XlsxReport) saveXlsx(file *xlsx.File, output string) string {
	var filename string
	if report.Filename != "" {
		filename = report.Filename
	} else {
		filename = defaultName()
	}

	filePath := fmt.Sprintf("%s/%s", output, filename)
	file.Save(filePath)
	return filePath
}

func (report *XlsxReport) CreateXlsx(path string, output string) (string, error) {
	fmt.Println(utils.CurrentTime())
	fileList, err := parse.ScanDir(path)
	if err != nil {
		return "", err
	}
	for _, name := range fileList {
		fileName := path + "/" + name
		hf := parse.LoadFile(fileName)
		bf := parse.LoadFile(fileName)
		table := &parse.Table{}
		table.GetHeader(hf)
		table.GetBody(bf)

		report.header = table.Header
		report.body = append(report.body, table.Body...)
		fmt.Printf("文件 %s 读取完成,共 %d 条记录\n", name, len(table.Body))
		hf.Close()
		bf.Close()
	}
	fmt.Printf("目录扫描完成,共 %d 条数据\n", len(report.body))

	xl := xlsx.NewFile()
	sheet, _ := xl.AddSheet("Sheet1")

	headers := make([][]string, 1)
	headers[0] = report.header
	report.addRowCell(sheet, headers)
	report.addRowCell(sheet, report.body)
	filename := report.saveXlsx(xl, output)

	fmt.Printf("\n生成excel文件成功,文件名: %s\n", filename)
	fmt.Println(utils.CurrentTime())

	return filename, nil
}
